import axios from "axios"
import {ElMessage} from 'element-plus'
import {router} from '../router'
import {UserApi} from "./urls";
import store from '../store/store'

axios.interceptors.request.use(function (config) {    // 这里的config包含每次请求的内容
  let token = getTokens().accessToken
  if (token) {
    config.headers.Authorization = token;
  }
  return config;
}, function (err) {
  return Promise.reject(err);
})


axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      console.error(error.response)
    }
    return Promise.reject(error)   // 返回接口返回的错误信息
  })

const checkTokens = ()=>{
  return getTokens()
}

/**
 *
 * @type {{accessToken:string,refreshToken:string}}
 * @private
 */
let __tokens = null

export const setTokens = (tokens) =>{
  __tokens = tokens
  tokens = JSON.stringify(tokens)
  localStorage.setItem("tokens",tokens)
  store.commit('logout')
}

export const getTokens = () => {
  if (__tokens){
    return __tokens;
  }
  let tokens = JSON.parse(localStorage.getItem("tokens"));
  if (!tokens) {
    tokens = {accessToken: null, refreshToken: null}
  }
  __tokens = tokens;
  return tokens;
}

export const removeLogin = ()=>{
  __tokens = null
  localStorage.removeItem("tokens")
  localStorage.removeItem("info")
  store.commit('logout')
}

/**
 *
 * @return {Promise<boolean>}
 */
const refreshLogin = async ()=>{
  let refreshToken = getTokens()?.refreshToken
  if (!refreshToken) {
    return false
  }
  return new Promise((resolve, reject) => {
    axios.post(UserApi.refresh,{refreshToken})
      .then((resp)=>{
        if (resp.data?.success){
          setTokens(resp.data.data)
          resolve(true)
        }else {
          resolve(false)
        }
      })
      .catch(e=>{
        console.error(e)
        resolve(false)
      })
  })

}

/**
 *
 * @param resp
 * @return {Promise<boolean>}
 */
const isTokenError = async (resp)=>{
  // console.log(resp)
  if (!resp.success && resp.message.startsWith('auth:')) {
    if (resp.data === 2 || resp.data === 4){
      removeLogin()
      //ElMessage.error("登录信息已失效，请重新登录")
    }else if (resp.data === 3){
      let result = await refreshLogin()
      console.log("refresh result :",result)
      if (!result) {
        removeLogin()
        //ElMessage.error("登录信息自动刷新失败，请重新登录")
      }
      return result
    }
  }
  return false
}


export const get = async function (url, data = {},ignoreLogin = false) {
  let cpy = data

  if (!ignoreLogin && !checkTokens()) {
    ElMessage.warning("您还未登录，请先登录")
    router.push("/login")
    return {success: false,message:"未登录"}
  }
  return new Promise((resolve, reject) => {
      axios.get(url, {params: data})
        .then(async resp =>{
          if (await isTokenError(resp.data)){
            resolve(await get(url,cpy,ignoreLogin))
          }
          resolve(resp.data)
        })
        .catch(e =>{
          console.error(e)
          resolve({success:false,message:"网络错误"})
        })
    }
  )
}


export const post = async function (url, data = {},ignoreLogin = false) {
  let cpy = data
  if (!ignoreLogin && !checkTokens()) {
    ElMessage.warning("您还未登录，请先登录")
    router.push("/login")
    return {success: false,message:"未登录"}
  }
  return new Promise((resolve, reject) => {
      axios.post(url, data)
        .then(async resp =>{
          if (await isTokenError(resp.data)){
            resolve(await post(url,cpy,ignoreLogin))
          }
          resolve(resp.data)
        })
        .catch(e =>{
          console.error(e)
          resolve({success:false,message:"网络错误"})
        })
    }
  )
}


export const put = async function (url, data = {},ignoreLogin = false) {
  let cpy = data
  if (!ignoreLogin && !checkTokens()) {
    ElMessage.warning("您还未登录，请先登录")
    router.push("/login")
    return {success: false,message:"未登录"}
  }
  return new Promise((resolve, reject) => {
      axios.put(url, data)
        .then(async resp =>{
          if (await isTokenError(resp.data)){
            resolve(await put(url,cpy,ignoreLogin))
          }
          resolve(resp.data)
        })
        .catch(e =>{
          console.error(e)
          resolve({success:false,message:"网络错误"})
        })
    }
  )
}
